<template>
  <div class="app-container">
    <el-button
      icon="el-icon-user"
      type="primary"
      @click="gotoAuth"
    >{{ $t('camera') + $t('auth') }}
    </el-button>
    <el-button
      icon="el-icon-camera-solid"
      type="primary"
      @click="dialogAuthDeviceVisible = true"
    >{{ $t('camera') + $t('list') }}
    </el-button>
    <el-button
      icon="el-icon-plus"
      type="primary"
      @click="camera={};dialogCameraFormVisible = true"
    />
    <el-table
      :data="deviceCameraList"
      style="width: 100%"
    >
      <el-table-column :label="$t('icon')" width="150">
        <template slot-scope="scope">
          <el-image
            style="width:90px;height: 60px;"
            :src="scope.row.picturePath"
            :preview-src-list="[scope.row.picturePath]"
            fit="fit"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" :label="$t('name')" />
      <el-table-column prop="hid" :label="$t('hid')" />
      <el-table-column prop="port" :label="$t('port')" />
      <el-table-column :label="$t('bind')+$t('device')">
        <template slot-scope="scope">
          <el-button
            @click="showBind(scope.row)"
          >{{ $t('edit') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column width="120" :label="$t('function')">
        <template slot-scope="scope">
          <el-link type="primary" @click="hls(scope.row)" v-text="$t('play')" />
          <el-link type="primary" @click="snap(scope.row)" v-text="$t('snap')" />
          <el-link type="primary" @click="showUpdate(scope.row)" v-text="$t('edit')" />
          <el-link type="primary" @click="historyImg(scope.row)" v-text="$t('history')" />
          <el-link type="danger" @click="del(scope.row)" v-text="$t('delete')" />
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 15px 0;text-align: right;">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogCameraFormVisible"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item :label="$t('user')">
          <el-select
            v-model="camera.authId"
            clearable
            filterable
          >
            <el-option
              v-for="(item,index) in authList"
              :key="index"
              :label="item.userName"
              :value="item.authId"
              :disabled="item.serverCompany!='none'"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('name')">
          <el-input v-model="camera.name" />
        </el-form-item>
        <el-form-item :label="$t('hid')">
          <el-input v-model="camera.hid" :disabled="camera.deviceId" />
        </el-form-item>
        <el-form-item :label="$t('port')">
          <el-input v-model="camera.port" />
        </el-form-item>
        <el-form-item label="rtmp">
          <el-input v-model="camera.rtmpUrl" />
        </el-form-item>
        <el-form-item label="rtmp HD">
          <el-input v-model="camera.rtmpHDUrl" />
        </el-form-item>
        <el-form-item label="hls">
          <el-input v-model="camera.hlsUrl" />
        </el-form-item>
        <el-form-item label="hls HD">
          <el-input v-model="camera.hlsHDUrl" />
        </el-form-item>
        <el-form-item label="flv">
          <el-input v-model="camera.httpFlvUrl" />
        </el-form-item>
        <el-form-item label="flv HD">
          <el-input v-model="camera.httpFlvHDUrl" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCameraFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="camera.hid"
      :visible.sync="playVideo"
      width="800px"
      top="5vh"
    >
      <camera-player
        v-if="playVideo"
        :device-id="camera.deviceId"
        type="video"
        height="450px"
        @onStop="playVideo=false"
      />
    </el-dialog>

    <el-dialog
      :title="camera.hid"
      :visible.sync="dialogSnapVisible"
      width="800px"
    >
      <camera-player
        v-if="dialogSnapVisible"
        type="picture"
        :device-id="camera.deviceId"
        height="450px"
        @onStop="playVideo=false"
      />
    </el-dialog>

    <el-dialog
      :title="camera.hid"
      :visible.sync="dialogBindVisible"
      width="800px"
    >
      <el-table
        :data="bindList"
        style="width: 100%;"
      >
        <el-table-column :label="$t('name')">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.name"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('deviceCore')">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.deviceCore"
            />
          </template>
        </el-table-column>
        <el-table-column>
          <template slot="header">
            <el-button
              type="primary"
              icon="el-icon-plus"
              style="float: right"
              @click="addBind"
            />
          </template>
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="updateBind(scope.row)"
            >{{ $t('save') }}
            </el-button>
            <el-button
              v-if="!scope.row.isAdd"
              type="danger"
              @click="deleteBind(scope.row)"
            >{{ $t('delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      top="15px"
      :visible.sync="dialogAuthDeviceVisible"
    >
      <el-tabs type="border-card" @tab-click="tabClick">
        <el-tab-pane v-for="(item,index) in authList" :key="index" :lazy="true" :label="item.userName">
          <el-table
            :data="item.cameraList"
            style="width: 100%"
          >
            <el-table-column
              prop="hid"
              :label="$t('hid')"
            />
            <el-table-column
              prop="port"
              :label="$t('port')"
            />
            <el-table-column width="220" :label="$t('function')">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-plus"
                  @click="add(scope.row)"
                >{{ $t('add') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  successNotice,
  cancelNotice
} from '@/util/common'
import {
  pageGetCameraDevice,
  deleteCameraDevice,
  updateCameraDevice,
  insertCameraDevice
} from '@/api/camera/cameraDeviceApi'
import { insertCameraBind, deleteCameraBind, updateCameraBind, listCameraBind } from '@/api/camera/cameraBindApi'
import { listCameraAuth, listCamera } from '@/api/camera/cameraAuthApi'
import { getUserId } from '@/util/storage'
import CameraPlayer from '@/components/CameraPlayer/index'
import { getPageSize, setPageSize } from '@/util/storage'

export default {
  name: 'CameraManage',
  components: {
    CameraPlayer
  },
  data() {
    return {
      dialogSnapVisible: false,
      authList: [],
      bindList: [],
      deviceCameraList: [],
      dialogBindVisible: false,
      dialogCameraFormVisible: false,
      dialogAuthDeviceVisible: false,
      camera: {
        name: null,
        deviceId: null,
        authId: null,
        hid: null,
        port: null,
        rtmpUrl: null,
        rtmpHDUrl: null,
        hlsUrl: null,
        hlsHDUrl: null,
        httpFlvUrl: null,
        httpFlvHDUrl: null
      },

      dialogTitle: '绑定设备',
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      playVideo: false,
      mediaType: null
    }
  },
  mounted() {
    const param = this.$route.query
    this.userId = getUserId()
    if (param != null) {
      if (param.userId != null) {
        this.userId = param.userId
      }
    }
    this.listCameraAuth()
    this.pageGetCameraDevice()
  },
  methods: {
    gotoAuth() {
      this.$router.push({
        path: '/camera/auth'
      })
    },
    add(item) {
      this.camera = item

      this.addOrUpdate()
    },
    tabClick(item) {
      console.log(item)
      this.listCamera(this.authList[item.index])
    },
    listCamera(item) {
      listCamera({
        authId: item.authId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          for (let i = 0, j = this.authList.length; i < j; i++) {
            if (this.authList[i].authId === item.authId) {
              const auth = this.authList[i]
              auth.cameraList = data
              this.authList.splice(i, 1, auth)
              break
            }
          }
        }
      })
    },
    showBind(item) {
      this.camera = item
      this.listCameraBind()
    },
    listCameraBind() {
      listCameraBind({ deviceId: this.camera.deviceId }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.bindList = data
          this.dialogBindVisible = true
        } else if (code === '201') {
          this.bindList = []
          this.dialogBindVisible = true
        }
      })
    },
    addBind() {
      for (let i = 0, j = this.bindList.length; i < j; i++) {
        if (this.bindList[i].isAdd) {
          return
        }
      }
      const item = {
        name: this.camera.hid,
        deviceCore: '',
        deviceId: this.camera.deviceId,
        isAdd: true
      }
      this.bindList.push(item)
    },
    updateBind(item) {
      if (item.isAdd) {
        insertCameraBind(item).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.listCameraBind()
          }
        })
      } else {
        updateCameraBind(item).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
          }
        })
      }
    },
    deleteBind(item) {
      const that = this
      this.$confirm(this.$t('delete') + this.$t('bind'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteCameraBind({
            bindId: item.bindId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              that.listCameraBind()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    listCameraAuth() {
      listCameraAuth({
        userId: this.userId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.authList = data
          this.listCamera(data[0])
        }
      })
    },
    snap(item) {
      this.camera = item
      this.dialogSnapVisible = true
    },
    showUpdate(item) {
      this.dialogTitle = this.$t('update')
      this.camera = item
      this.dialogCameraFormVisible = true
    },
    addOrUpdate() {
      const json = {
        ...this.camera
      }
      if (!this.camera.deviceId) {
        insertCameraDevice(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.pageGetCameraDevice()
            this.dialogCameraFormVisible = false
          }
        })
      } else {
        json.deviceId = this.camera.deviceId
        updateCameraDevice(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.pageGetCameraDevice()
            this.dialogCameraFormVisible = false
          }
        })
      }
    },
    historyImg(item) {
      this.$router.push({
        path: '/camera/img/' + item.deviceId,
        query: { deviceId: item.deviceId, hid: item.hid }
      })
    },
    hls(item) {
      console.log('播放' + item.hid)
      this.camera = item
      this.mediaType = 'hls'
      this.playVideo = true
    },
    rtmp(item) {
      this.camera = item
      this.mediaType = 'rtmp'
      this.playVideo = true
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetCameraDevice()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetCameraDevice()
    },
    pageGetCameraDevice() {
      pageGetCameraDevice({
        deviceCore: this.deviceCore,
        userId: this.userId,
        pageSize: this.pageSize,
        currentPage: this.currentPage
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          const deviceCameraList = data.data
          this.deviceCameraList = deviceCameraList
        }
      })
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete') + this.$t('camera'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteCameraDevice({
            deviceId: item.deviceId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetCameraDevice()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>
